package com.acane.instagram.feature.notification

import android.util.Log
import androidx.compose.runtime.mutableStateOf
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.acane.instagram.core.config.NotificationManager
import com.acane.instagram.core.config.WebSocketManager
import com.acane.instagram.core.model.Notification
import com.acane.instagram.core.model.network.datasource.MyRetrofitDatasource
import com.acane.instagram.feature.chat.ChatWebSocketClient
import com.acane.instagram.feature.common.SessionManager
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import okhttp3.Response

class NotificationViewModel(

): ViewModel(), ChatWebSocketClient.Listener  {

    private val _isConnected = mutableStateOf(false)
    private val _notificationDatum =  MutableStateFlow<List<Notification>>(emptyList())
    val notificationDatum: MutableStateFlow<List<Notification>> = _notificationDatum

    private val _commentNotification =  MutableStateFlow<List<Notification.CommentNotification?>>(emptyList())
    val commentNotification: MutableStateFlow<List<Notification.CommentNotification?>> = _commentNotification

    init {
        WebSocketManager.addListener(this) // 注册全局监听
        loadNotification()
        // 首次连接检查
        checkInitialConnection()
    }

    private fun checkInitialConnection() {
        viewModelScope.launch {
            if (WebSocketManager.isConnected.not()) {
                SessionManager._sessionId?.let {
                    WebSocketManager.connect(it)
                }
            }
        }
    }

    fun sendMessageNotification(commenterId: String, postId: String, content: String) {
        viewModelScope.launch {
            try {
                // 在需要发送通知的地方调用
                val notification = Notification.CommentNotification(
                    id = "",
                    timestamp = "",
                    content = content,
                    postId = postId,
                    commenterId = commenterId,
                    likes = 0,
                    parentId = ""
                )
                WebSocketManager.sendNotification(notification)
                Log.d("NotificationViewModel", "发送评论通知\n${notification}")
            } catch (e: Exception) {
                Log.e("NotificationViewModel", "发送失败: ${e.message}")
            }
        }
    }

    fun sendReplyMessageNotification(commenterId: String, postId: String, content: String, replyId: String) {
        viewModelScope.launch {
            try {
                // 在需要发送通知的地方调用
                val notification = Notification.CommentNotification(
                    id = "",
                    timestamp = "",
                    content = content,
                    postId = postId,
                    commenterId = commenterId,
                    likes = 0,
                    parentId = replyId
                )
                WebSocketManager.sendNotification(notification)
                Log.d("NotificationViewModel", "发送评论通知\n${notification}")
            } catch (e: Exception) {
                Log.e("NotificationViewModel", "发送失败: ${e.message}")
            }
        }
    }

    fun sendLikeNotification(likerId: String, postId: String) {
        viewModelScope.launch {
            try {
                // 在需要发送通知的地方调用
                val notification = Notification.LikeNotification(
                    id = "",
                    timestamp = "",
                    postId = postId,
                    likerId = likerId
                )
                WebSocketManager.sendNotification(notification)
                Log.d("NotificationViewModel", "发送点赞帖子通知\n${notification}")
            } catch (e: Exception) {
                Log.e("NotificationViewModel", "发送失败: ${e.message}")
            }
        }
    }

    fun sendCommentLikeNotification(likerId: String, commentId: String) {
        viewModelScope.launch {
            try {
                // 在需要发送通知的地方调用
                val notification = Notification.CommentLikeNotification(
                    id = "",
                    timestamp = "",
                    commentId = commentId,
                    likerId = likerId
                )
                WebSocketManager.sendNotification(notification)
                Log.d("NotificationViewModel", "发送点赞评论通知\n${notification}")
            } catch (e: Exception) {
                Log.e("NotificationViewModel", "发送失败: ${e.message}")
            }
        }
    }


    // 修改 onMessageReceived 方法，强制主线程更新
    override fun onMessageReceived(message: Notification) {
        Log.d("NotificationViewModel", "收到通知: $message")
        viewModelScope.launch(Dispatchers.Main) {
            updateNotification(message)
            Log.d("NotificationViewModel", "更新通知: ${_notificationDatum.value}")
            // 非聊天消息转交给通知管理器
            NotificationManager.handleNotification(message)
        }
    }

    // 修改 updateMessages 方法，基于消息 ID 去重
    private fun updateNotification(newNotification: Notification) {
        val updatedMessages = mutableListOf<Notification>().apply {
            add(newNotification)
            addAll(_notificationDatum.value)
        }
        // 更新评论数据
        _commentNotification.value = updatedMessages.filterIsInstance<Notification.CommentNotification>()
        _notificationDatum.value = updatedMessages.sortedByDescending { it.timestamp }
    }

    fun loadNotification() {
        viewModelScope.launch {
            try {
                val userId = SessionManager.currentUser?.id
                // 从数据库获取记录
                val commentHistory = userId?.let { MyRetrofitDatasource.getCommentHistory(it) }
                val likeHistory = userId?.let { MyRetrofitDatasource.getLikeHistory(it) }
                val followHistory = userId?.let { MyRetrofitDatasource.getFollowHistory(it) }
                val commentLikeHistory = userId?.let { MyRetrofitDatasource.getCommentLikeHistory(it) }

                // 合并多个数据源的完整实现
                _notificationDatum.value = listOf(
                    commentLikeHistory?.data?.map {
                        Notification.CommentLikeNotification(
                            id = it.id,
                            commentId = it.commentId,
                            likerId = it.likerId,
                            timestamp = it.timestamp
                        )
                    }.orEmpty(),

                    commentHistory?.data?.map {
                        Notification.CommentNotification(
                            id = it.id,
                            postId = it.postId,
                            commenterId = it.commenterId,
                            content = it.content,
                            timestamp = it.timestamp,
                            likes = it.likes,
                            parentId = it.parentId
                        )
                    }.orEmpty(),

                    likeHistory?.data?.map {
                        Notification.LikeNotification(
                            id = it.id,
                            postId = it.postId,
                            likerId = it.likerId,
                            timestamp = it.timestamp
                        )
                    }.orEmpty(),

                    followHistory?.data?.map {
                        // 需要先创建 FollowNotification 子类（在 Notification.kt 中新增）
                        Notification.FollowNotification(
                            id = it.id,
                            followerId = it.followerId,
                            createTime = it.createTime,
                            updateTime = it.updateTime,
                            followingId = it.followingId,
                            timestamp = ""
                        )
                    }.orEmpty()
                ).flatten()
                    .sortedByDescending { it.timestamp } // 按时间降序排列

                // 加载评论WS数据
                _commentNotification.value = _notificationDatum.value.filterIsInstance<Notification.CommentNotification>()
                Log.d("NotificationViewModel", "加载历史通知: ${_notificationDatum.value}")
            } catch (e: Exception) {
                // Handle error
                println("Failed to load chat history: ${e.message}")
            }
        }
    }
    override fun onConnected() {
        _isConnected.value = true
    }

    override fun onClosed(code: Int, reason: String) {
        _isConnected.value = false
        println("WebSocket closed: $code, $reason")
    }

    override fun onFailure(t: Throwable, response: Response?) {
        _isConnected.value = false
        println("WebSocket connection failed: ${t.message}")
    }


}